#include "lineeditdelegate.h"

#include <QLineEdit>
#include <QPainter>

//! [0]
LineEditDelegate::LineEditDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{

}
//! [0]

//! [1]
QWidget *LineEditDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem &/* option */,
    const QModelIndex &/* index */) const
{
    QLineEdit *editor = new QLineEdit(parent);
    editor->setFrame(false);
    QRegExp rx("^\\d{1,6}[.](\\d{2})$");
    QValidator *validator = new QRegExpValidator(rx);
    editor->setValidator(validator);
    editor->setAlignment(Qt::AlignRight);

    return editor;
}
//! [1]

//! [2]
void LineEditDelegate::setEditorData(QWidget *editor,
                                    const QModelIndex &index) const
{
    QString value = index.model()->data(index, Qt::EditRole).toString();

    QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
    lineEdit->setAlignment(Qt::AlignRight);
    lineEdit->setText(value);
}
//! [2]

//! [3]
void LineEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
    QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
    //lineEdit->interpretText();
    QString text = lineEdit->text();

    model->setData(index, text, Qt::EditRole);
}
//! [3]

//! [4]
void LineEditDelegate::updateEditorGeometry(QWidget *editor,
    const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{

    editor->setGeometry(option.rect);
}
//! [4]

void LineEditDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                         const QModelIndex &index) const
{

    QStyleOptionViewItem myOption = option;
    myOption.displayAlignment = Qt::AlignRight | Qt::AlignCenter;
    QStyledItemDelegate::paint(painter, myOption, index);
}
